package com.dm.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.ObjectUtil;
import com.dm.domain.SysUser;
import com.dm.mapper.SysUserMapper;
import com.dm.util.AjaxResult;
import com.dm.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tjw
 * @date 2024-10-05
 * @Description
 */

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;



    @RequestMapping("/logout/{satoken}")
    public void logout(@PathVariable("satoken") String satoken){
        StpUtil.logoutByTokenValue(satoken);
    }

    @RequestMapping("/login")
    public AjaxResult login( @RequestBody SysUser userDTO){

        String code = stringRedisTemplate.opsForValue().get("captchat_code:" + userDTO.getUuid());
        String code1 = userDTO.getCode();
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(code1) || !code.equals(code1)) {
            return AjaxResult.error(201, "验证码错误!");
        }
        SysUser sysUser = sysUserMapper.selectUser(userDTO.getUsername());
        if (ObjectUtil.isEmpty(sysUser)){
            return AjaxResult.error(201,"用户不存在!");
        }
        if (!sysUser.getPw().equals(userDTO.getPassword())) {
            return AjaxResult.error(201,"密码错误!");
        }
        StpUtil.login(sysUser.getUserId(), true);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        // 返回数据对象
        Map<String,Object> map = new HashMap<>();
        map.put("user", sysUser);
        map.put("tokenInfo", tokenInfo);
        return AjaxResult.success("登录成功!", map);
    }


}
